package logic

import (
	"activity/activityRpc/activityRpc"
	"activity/activityRpc/internal/svc"
	"activity/models/cache"
	"activity/models/mysql"
	"context"
	"encoding/json"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"time"
)

type ListActivityLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListActivityLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListActivityLogic {
	return &ListActivityLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListActivityLogic) ListActivity(in *activityRpc.ListActivityRequest) (*activityRpc.ListActivityResponse, error) {
	// todo: add your logic here and delete this line

	var page int64
	var pageSize int64

	if page <= 0 {
		page = 1
	}

	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}
	offset := (page - 1) * pageSize

	var activitys []mysql.Activity

	key := fmt.Sprintf("listActivitys_%d_%d", in.Page, in.Size)
	cacheData, _ := cache.Rdb.Get(l.ctx, key).Result()
	if cacheData == "" {

		mysql.DB.Find(&activitys).
			Offset(int(offset)).Limit(int(pageSize)).
			Order("created_at desa")
		jsonData, _ := json.Marshal(activitys)
		cache.Rdb.Set(l.ctx, key, jsonData, time.Minute)
	} else {
		json.Unmarshal([]byte(cacheData), &activitys)
	}

	var listactivitys []*activityRpc.ListActivity
	for _, activity := range activitys {
		list := activityRpc.ListActivity{
			Title:         activity.Title,
			ActivityImage: activity.ActivityImage,
			Info:          activity.Info,
			UserId:        int64(activity.UserId),
		}
		listactivitys = append(listactivitys, &list)
	}

	return &activityRpc.ListActivityResponse{
		List: listactivitys,
	}, nil
}
